package com.wang.openApiclientsdk.client;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.wang.openApiCommon.common.BaseResponse;
import com.wang.openApiclientsdk.common.HttpConstant;
import com.wang.openApiclientsdk.service.GlobalUtil;
import com.wang.openApiclientsdk.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 客户端
 * 会先被网关拦截，通过网关验证之后再转发到interface服务上
 */
public class OpenApiClient {

    /**
     * 公钥和私钥
     */
    private String accessKey;
    private String secretKey;

    private GlobalUtil globalUtil = new GlobalUtil();


    public OpenApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * 无参返回随机数
     *
     * @return
     */
    public BaseResponse<String> getRandomByGet() {
        return globalUtil.getRandomByGet();
    }

    /**
     * 返回指定长度的随机数
     *
     * @param length
     * @return
     */
    public BaseResponse<String> getRandomLengthByGet(String length) {
        return globalUtil.getRandomLengthByGet(length);
    }

    public String getNameByGet(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String result = HttpUtil.get(HttpConstant.prefix + "/api/name/", hashMap);
        System.out.println("getNameByGet: " + result);
        return result;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", name);
        String result = HttpUtil.post("http://localhost:8090/api/name/", hashMap);
        System.out.println("getNameByPost: " + result);
        return result;
    }

    private Map<String, String> getHeaderMap(String body) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        hashMap.put("secretKey", secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", SignUtils.getSign(body, secretKey)); //签名
        return hashMap;
    }

//    public String getUsernameByPost(User user) {
//        String jsonStr = JSONUtil.toJsonStr(user);
//        System.out.println("getUsernameByPost: " + jsonStr); //getUsernameByPost: {"username":"123"}
//        //{"username":"123"}  {"username":"123"}
//        /**
//         * 这里先走网关，通过网关校验再调用实际地址
//         * todo 这里的接口地址应该是根据客户端传过来的地址 而不是写死在这里
//         */
//        String interfaceUrl = "http://localhost:8090/api/name/user";
//        HttpResponse httpResponse = HttpRequest.post(interfaceUrl)
//                .addHeaders(getHeaderMap(jsonStr))
//                .body(jsonStr)
//                .execute();
//
////        System.out.println("http status: " + httpResponse.getStatus());
//        String body = httpResponse.body();
//        return body;
//    }

}
